package com.zbu.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbu.common.core.constants.Constants;
import com.zbu.common.core.domain.TableDataInfo;
import com.zbu.common.core.enums.ExamListType;
import com.zbu.common.core.enums.ResultCode;
import com.zbu.common.core.utils.ThreadLocalUtil;
import com.zbu.common.security.exception.ServiceException;
import com.zbu.common.security.service.TokenService;
import com.zbu.friend.domain.exam.Exam;
import com.zbu.friend.domain.exam.dto.ExamDTO;
import com.zbu.friend.domain.exam.dto.ExamQueryDTO;
import com.zbu.friend.domain.exam.vo.ExamVO;
import com.zbu.friend.domain.user.UserExam;
import com.zbu.friend.domain.user.vo.UserVO;
import com.zbu.friend.manager.ExamCacheManager;
import com.zbu.friend.manager.UserCacheManager;
import com.zbu.friend.mapper.exam.ExamMapper;
import com.zbu.friend.mapper.user.UserExamMapper;
import com.zbu.friend.service.user.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamService implements IUserExamService {
    @Autowired
    ExamMapper examMapper;
    @Autowired
    UserExamMapper userExamMapper;
    @Autowired
    TokenService tokenService;
    @Autowired
    ExamCacheManager examCacheManager;
    @Value("${jwt.secret}")
    private String secret;
    private UserCacheManager userCacheManager;
    @Override
    public int  enter(String token, Long examId) {
//        //获取当前用户的信息
//        Long userId=ThreadLocalUtil.get(Constants.USER_ID,Long.class);
//        UserVO userVO=userCacheManager.getUserById(userId);
//        if(userVO.getStatus()==0){
//                throw  new ServiceException(ResultCode.FAILED_USER_BANNED);
//        }

        Exam exam=examMapper.selectById(examId);
        if(exam==null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        if(exam.getStartTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
        //Long userId=tokenService.getUserId(token,secret);
        Long userId= ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        UserExam userExam=userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId,examId)
                .eq(UserExam::getUserId,userId));
        if(userExam!=null){
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        examCacheManager.addUserExamCache(userId, examId);
        userExam=new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }



    //先查询缓存 ("u:e:l"用户ID)
    //如果查询不到就到数据库中查询.并且将数据库中的内容同步到redis
    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        Long userId=ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);
        List<ExamVO> examVOList;
        if(total==null||total<=0){
            PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
            //从数据库查询竞赛列表
            examVOList=userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(),null);
            total=new PageInfo<>(examVOList).getTotal();
        }else{
            examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
            examVOList=examCacheManager.getExamVOList(examQueryDTO,userId);
            total=examCacheManager.getListSize(examQueryDTO.getType(),userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
//        new PageInfo<>(list).getTotal(); //获取符合查询条件的数据的总数
//        return TableDataInfo.success(list, list.size());
        return TableDataInfo.success(examVOList,total );
    }
}
